<script setup>
  import { ref, onMounted } from 'vue'
  import { getListApi } from '@/apis/message'

  // 1. 获取列表数据
  // 数据数组
  const notifyList = ref([])
  // 下一页的页码
  const nextPage = ref(1)
  // 每页显示的条数
  const pageSize = ref(5)
  // 数据是否为空
  const isEmpty = ref(false)
  // 是否有更多数据
  const hasMore = ref(true)

  const getNotifyList = async (page = 1, pageSize = 5) => {
    const { code, data } = await getListApi(201, page, pageSize)
    if (code !== 200) return uni.utils.toast()
    // 判断: 如果是请求第一页的数据(清空数据数组)
    if (page === 1) notifyList.value = []
    // 渲染数据
    notifyList.value = [...notifyList.value, ...(data.items || [])]
    // 更新下一页页码
    nextPage.value = ++data.page
    // 判断数据数组是否为空
    isEmpty.value = data.items.length === 0
    // 处理是否有更多的数据
    hasMore.value = nextPage.value <= data.pages
  }

  onMounted(() => {
    getNotifyList()
  })

  // 2. 上拉加载
  const onScrolltolower = () => {
    //2.1 判断是否有更多的数据
    if (!hasMore.value) return uni.utils.toast('没有更多的数据了~')
    // 2.2 加载下一页数据
    getNotifyList(nextPage.value)
  }

  // 3. 下拉刷新
  // 是否打开下拉交互
  const isTriggered = ref(false)
  const onRefresh = async () => {
    isTriggered.value = true
    await getNotifyList()
    isTriggered.value = false
  }
</script>
<template>
  <scroll-view
    class="scroll-view"
    refresher-enabled
    scroll-y
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrolltolower"
    @refresherrefresh="onRefresh"
  >
    <view class="scroll-view-wrapper">
      <view class="message-action">
        <text class="iconfont icon-clear"></text>
        全部已读
      </view>
      <uni-card
        v-for="item in notifyList"
        :key="item.id"
        :border="false"
        :is-shadow="false"
      >
        <view class="brief">{{ item.content }}</view>
        <view class="extra">
          <text class="time">{{ item.created }}</text>
          <navigator
            hover-class="none"
            class="link"
            :url="`/subpkg_message/content/index?id=${item.id}`"
            >查看详情</navigator
          >
        </view>
        <template v-slot:title>
          <view class="title" :class="{ unread: item.isRead === 0 }">{{
            item.title
          }}</view>
        </template>
      </uni-card>
      <view v-if="isEmpty" class="message-blank">暂无消息</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
